var express = require('express');
const { post, route } = require('.');
var router = express.Router();

const userService = require('../service/userService');
/* GET users listing. */
// router.get('/', function (req, res, next) {
//   res.send('respond with a resource');
// });

//注册
router.post('/reg', async function (req, res) {
  let { username, password, phone, email, privilege } = req.body;//获取数据
  let data = await userService.insert({ username, password, phone, email, privilege });//这里用的解构方法，属性名：属性值，用语法糖简写
  res.send(data);
});

//判断用户名是否存在
router.post('/usernameExist', async function (req, res) {
  let { username, password } = req.body;
  let data = await userService.findByUsernameAndPassword({ username, password });
  if (data.length > 0) {//如果用户名的长度大于0则代表用户名已经存在了
    res.send({ status: 0 });
  } else {//如果用户没有重复则注册
    res.send({ status: 1 });
    // let data =await userService.insert({username,password, age});
    // res.send(data);
  }
});


//登录
router.post('/login', async function (req, res) {
  let { username, password } = req.body;
  let data = await userService.findByUsernameAndPassword({ username, password });
  console.log(data);
  if (data.length > 0) {
    req.session.user = data[0];//是一个用户对象 data是一个数组，data[0]就是数组里面的每一个对象{id:,username:,password:}
    res.send({ status: 1, data });
  } else {
    res.send({ status: 0, data });
  }
  // res.send(data);
});

//新增
router.post('/', async function (req, res) {
  let { username, password, phone, email } = req.body;//获取数据
  let data = await userService.insert({ username, password, phone, email });
  res.send(data);
});

//查询所有
router.get('/', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchParams = {};
  searchParams[type] = value;
  let data = await userService.find({ current: current || 1, pageSize: pageSize || 5 }, searchParams);
  res.send(data);
});

//按id查询
router.get('/:id', async function (req, res) {
  let { id } = req.params;//获取路径后面的变量用params
  let data = await userService.findById(id);
  res.send(data);
});

//删除
router.delete('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.delete(id);
  res.send(data);
});

//修改
router.put('/:id', async function (req, res) {
  let { id } = req.params;
  let { username, password, phone, email } = req.body;
  let data = await userService.update({ _id: id, username, password, phone, email });
  res.send(data);
});

module.exports = router;
